package com.qimu.saiyou.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qimu.saiyou.annotation.AuthCheck;
import com.qimu.saiyou.common.BaseResponse;
import com.qimu.saiyou.common.DeleteRequest;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.common.ResultUtils;
import com.qimu.saiyou.constant.UserConstant;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.manager.RedisLimiterManager;
import com.qimu.saiyou.model.dto.team.*;
import com.qimu.saiyou.model.entity.Chat;
import com.qimu.saiyou.model.entity.Team;
import com.qimu.saiyou.model.entity.User;
import com.qimu.saiyou.model.enums.TeamRoleEnum;
import com.qimu.saiyou.model.vo.TeamVO;
import com.qimu.saiyou.service.ChatService;
import com.qimu.saiyou.service.TeamService;
import com.qimu.saiyou.service.UserService;
import com.qimu.saiyou.utils.RedissonLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 队伍接口
 *
 *@author: FeiXiang
 *
 */
@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {
    @Resource
    private RedissonLockUtil redissonLockUtil;
    @Resource
    private TeamService teamService;
    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private UserService userService;

    @Resource
    private ChatService chatService;

    // region 增删改查

    /**
     * 创建
     *
     * @param teamAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        redisLimiterManager.doRateLimit("addTeam_" + loginUser.getUserAccount());
        return redissonLockUtil.redissonDistributedLocks("saiyou:addTeam:" + loginUser.getId(), () -> {
            Team team = new Team();
            BeanUtils.copyProperties(teamAddRequest, team);
            List<String> tags = teamAddRequest.getTags();
            if (tags != null) {
                team.setTags(JSONUtil.toJsonStr(tags));
            }
            List<String> wantToTags = teamAddRequest.getWantToTags();
            if (tags != null) {
                team.setWantToTags(JSONUtil.toJsonStr(wantToTags));
            }
            teamService.validTeam(team, true);
            Long count = teamService.lambdaQuery().like(Team::getUsersId, loginUser.getId()).count();
            if (count >= 5) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "最多只能创建并最多加入5只队伍");
            }
            team.setTeamLeaderId(loginUser.getId());
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(loginUser.getId());
            team.setUsersId(JSONUtil.toJsonStr(userIdList));
            boolean result = teamService.save(team);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            long newTeamId = team.getId();
            return ResultUtils.success(newTeamId);
        });
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅带队老师或管理员可删除
        if (!oldTeam.getTeamLeaderId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        chatService.remove(new LambdaQueryWrapper<Chat>().eq(Chat::getTeamId, oldTeam.getId()));
        boolean b = teamService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param teamUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null || teamUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamUpdateRequest, team);
        List<String> tags = teamUpdateRequest.getTags();
        if (tags != null) {
            team.setTags(JSONUtil.toJsonStr(tags));
        }
        List<String> wantToTags = teamUpdateRequest.getWantToTags();
        if (tags != null) {
            team.setWantToTags(JSONUtil.toJsonStr(wantToTags));
        }
        // 参数校验
        teamService.validTeam(team, false);
        long id = teamUpdateRequest.getId();
        // 判断是否存在
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getId().equals(oldTeam.getTeamCaptainId()) && !loginUser.getId().equals(oldTeam.getTeamLeaderId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = teamService.updateById(team);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TeamVO> getTeamVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(teamService.getTeamVO(team, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param teamQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Team>> listTeamByPage(@RequestBody TeamQueryRequest teamQueryRequest) {
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getQueryWrapper(teamQueryRequest));
        return ResultUtils.success(teamPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TeamVO>> listTeamVOByPage(@RequestBody TeamQueryRequest teamQueryRequest,
                                                       HttpServletRequest request) {
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getQueryWrapper(teamQueryRequest));
        return ResultUtils.success(teamService.getTeamVOPage(teamPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TeamVO>> listMyTeamVOByPage(@RequestBody TeamQueryRequest teamQueryRequest,
                                                         HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQueryRequest.setUserId(loginUser.getId());
        long current = teamQueryRequest.getCurrent();
        long size = teamQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Team> teamPage = teamService.page(new Page<>(current, size),
                teamService.getQueryWrapper(teamQueryRequest));
        return ResultUtils.success(teamService.getTeamVOPage(teamPage, request));
    }

    @PostMapping("/edit")
    public BaseResponse<Boolean> editTeam(@RequestBody TeamEditRequest teamEditRequest, HttpServletRequest request) {
        if (teamEditRequest == null || teamEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamEditRequest, team);
        List<String> tags = teamEditRequest.getTags();
        if (tags != null) {
            team.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        teamService.validTeam(team, false);
        User loginUser = userService.getLoginUser(request);
        long id = teamEditRequest.getId();
        // 判断是否存在
        Team oldTeam = teamService.getById(id);
        ThrowUtils.throwIf(oldTeam == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTeam.getTeamLeaderId().equals(loginUser.getId()) && !userService.isAdmin(loginUser) && oldTeam.getTeamCaptainId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = teamService.updateById(team);
        return ResultUtils.success(result);
    }
    // endregion

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest joinTeam, HttpServletRequest request) {
        if (joinTeam == null || joinTeam.getTeamId() == null || joinTeam.getTeamId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean join = teamService.joinTeam(joinTeam, loginUser);
        return ResultUtils.success(join);
    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(Long teamId, HttpServletRequest request) {
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean quitTeam = teamService.quitTeam(teamId, request);
        return ResultUtils.success(quitTeam);
    }

    /**
     * 踢出队
     *
     * @param request            要求
     * @param teamKickOutRequest 退出团队请求
     * @return {@link BaseResponse}<{@link Boolean}>
     */
    @PostMapping("/kickOutTeam")
    public BaseResponse<Boolean> kickOutTeam(@RequestBody TeamKickOutRequest teamKickOutRequest, HttpServletRequest request) {
        if (teamKickOutRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (teamKickOutRequest.getTeamId() == null || teamKickOutRequest.getTeamId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (teamKickOutRequest.getUserId() == null || teamKickOutRequest.getUserId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean kickOutTeam = teamService.kickOutTeam(teamKickOutRequest, request);
        return ResultUtils.success(kickOutTeam);
    }

    @PostMapping("/teamTransferOfIdentity")
    public BaseResponse<Boolean> teamTransferOfIdentity(@RequestBody TeamTransferOfIdentityRequest teamTransferOfIdentityRequest, HttpServletRequest request) {
        if (teamTransferOfIdentityRequest == null || teamTransferOfIdentityRequest.getTeamId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(teamTransferOfIdentityRequest.getToUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(teamTransferOfIdentityRequest.getType())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "类型有误");
        }
        List<String> teamRoleList = TeamRoleEnum.getValues();
        if (!teamRoleList.contains(teamTransferOfIdentityRequest.getType())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该职位不存在");
        }
        boolean transferOfIdentity = teamService.teamAdminTransferOfIdentity(teamTransferOfIdentityRequest, request);
        return ResultUtils.success(transferOfIdentity);
    }

    @PostMapping("/teamCancelCaptain")
    public BaseResponse<Boolean> teamCancelCaptain(@RequestBody TeamTransferOfIdentityRequest teamTransferOfIdentityRequest, HttpServletRequest request) {
        if (teamTransferOfIdentityRequest == null || teamTransferOfIdentityRequest.getTeamId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(teamTransferOfIdentityRequest.getToUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isBlank(teamTransferOfIdentityRequest.getType())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "类型有误");
        }
        List<String> teamRoleList = TeamRoleEnum.getValues();
        if (!teamRoleList.contains(teamTransferOfIdentityRequest.getType())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该职位不存在");
        }
        boolean transferOfIdentity = teamService.teamCancelCaptain(teamTransferOfIdentityRequest, request);
        return ResultUtils.success(transferOfIdentity);
    }
}
